<template>
  <layout-card
    class="layoutCard"
    v-model="search"
    :filters="ismapOptions"
    headline="信息列表"
    headtitle="数据筛选"
    :hasButton="true"
    @search-change="getData"
    @search-reset="searchReset"
  >
    <template #action>
      <el-button type="primary" @click="handleCreate('threshold')">数量阈值</el-button>
      <el-button type="primary" @click="handleCreate('export')" :disabled="!tabledata.length">导出</el-button>
      <el-button type="primary" @click="handleCreate('download')">模版下载</el-button>
      <el-upload
        style="display: inline-block;margin-left: 12px;margin-right: 12px;"
        ref="upload"
        :auto-upload="false"
        :on-change="handleImport"
        :show-file-list="false"
        accept=".xlsx, .xls"
      >
        <el-button type="primary" @click="handleCreate('import')">导入</el-button>
      </el-upload>
      <el-button type="primary" @click="handleCreate('add')">新增设备</el-button>
    </template>
    <table-common
      stripe="true"
      :columns="mapListColumns"
      :loading="loading"
      :pagination="pager"
      :table-data="tabledata"
      size="large"
      @current-change="changeCurrent"
      @size-change="changePageSize"
    >
      <template #action="{ row }">
        <!-- 自定义操作栏示例  -->
        <el-button class="link-btn" @click="handleEdit(row)" link type="primary">编辑</el-button>
        <el-popconfirm
          title="是否删除?"
          confirmButtonText="确定"
          cancelButtonText="取消"
          @confirm="() => DeletRow(row)"
        >
          <template #reference>
            <el-button class="link-btn" link type="danger">删除</el-button>
          </template>
        </el-popconfirm>
      </template>
    </table-common>
  </layout-card>
  <edit-dialog
    :close-on-click-modal="false"
    :centerDialogVisible="thresholdDialogVisible"
    :tilte="addTilte"
    :key="timer"
    :defaultButton="false"
    :width="500"
    style="height: 100px"
    @Cancel="handleCancel"
  >
    <template #content>
      <el-table :data="thresholdData" :pagination="false" height="200px" @row-click="hiddenMe">
        <el-table-column type="index" label="序号" width="60" align="center"/>
        <template v-for="(item, colIndex) in thresholdListColumns" :key="colIndex">
          <el-table-column :label="item.label" :prop="item.prop" :width="item.width" align="center">
            <template #default="scope">
              <el-input-number
                v-if="isEdit && scope.$index === rowInd && scope.cellIndex === colInd"
                v-model="scope.row[item.prop]"
                size="small"
                style="width: 80px"
                controls-position="right"
                @click.stop
              />
              <el-select
                v-else-if="isSelect && scope.$index === rowInd && scope.cellIndex === colInd"
                v-model="scope.row[item.prop]"
                size="small"
              >
                <el-option key="1" label="是" value="是" />
                <el-option key="2" label="否" value="否" />
              </el-select>
              <div
                v-else
                @click="cellClick(scope)"
                style="width: 50px; height: 24px"
              >{{ scope.row[item.prop] }}</div>
            </template>
          </el-table-column>
        </template>
      </el-table>
    </template>
    <template #custom>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </span>
    </template>
  </edit-dialog>
  <edit-dialog
    :close-on-click-modal="false"
    :centerDialogVisible="addDialogVisible"
    :tilte="addTilte"
    :key="timer"
    :defaultButton="false"
    :width="950"
    style="height: 100px"
    @Cancel="handleCancel"
  >
    <template #content>
      <div style="width: 100%; height: 500px; border: 1px solid #000">
        <map-control @mapClick="mapClick"></map-control>
      </div>
    </template>
    <template #custom>
      <span class="dialog-footer">
        <el-button class="buttonCancel" @click="handleCancel">取消</el-button>
        <el-button class="buttonOk" type="primary" @click="handleNext">下一步</el-button>
        <el-button class="buttonOk" @click="handleNext" plain>跳过</el-button>
      </span>
    </template>
  </edit-dialog>
  <edit-dialog
    :close-on-click-modal="false"
    :centerDialogVisible="saveDialogVisible"
    :tilte="addTilte"
    :key="timer"
    :defaultButton="false"
    :width="950"
    style="height: 100px"
    @Cancel="handleCancel"
    :rules="rules"
  >
    <template #content>
      <filter-bar
        :filters="isdialogOptions"
        :hasButton="false"
        :rules="rules"
        ref="FilterRef"
        :close-collapse="true"
        @on-toggle="(val) => $emit('on-toggle', val)"
      ></filter-bar>
    </template>
    <template #custom>
      <span class="dialog-footer">
        <el-button class="buttonCancel" @click="handleCancel">取消</el-button>
        <el-button class="buttonOk" @click="handleBack">返回</el-button>
        <el-button class="buttonOk" type="primary" @click="handleSave">保存</el-button>
      </span>
    </template>
  </edit-dialog>
</template>

<script lang="ts" setup>
import FilterBar from "@/components/FilterBar/index.vue";
import { computed, ref, reactive, onBeforeMount, nextTick } from "vue";
import LayoutCard from "@/components/LayoutCard/index.vue";
import TableCommon from "@/components/TableCommon/index.vue";
import editDialog from "@/components/editDialog/index.vue";
import { useStore } from "vuex";
import {
  mapListColumns,
  thresholdListColumns
} from "@/views/eqpt/seat/config/columns";
import { mapOptions, dialogOptions } from "@/views/eqpt/seat/config/filters";
import {
  seatPageList,
  seatDeleteRow,
  seatModuleDown,
  seatImport,
  exportPageList,
  append,
  change,
  geteqptType
} from "@/api/eqpt/seat.ts";
import { usePagination } from "vue-request";
import { FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import { getResource } from "@/api/resource";

import mapControl from "@/components/map/index.vue";
import { store } from "@/components/map/mapStore";
import { image } from "@/assets/index";
import { UploadInstance } from "element-plus";
import { getOrganName } from "@/utils/common";

const FilterRef = ref({});
const isdialogOptions = ref(dialogOptions);
//归属单位map对象
const mapList = new Map();
//请求用户的权限树
let { getters } = useStore();
// 拿到vuex里面用户的信息
const organInfo = computed(() => getters["user/getOrganTree"]);
const Users = computed(() => getters["user/getUserInfo"]);
var typeId = "";

const stores = useStore();
const organTree = stores.state.user.organTree; //获取树
//获取使用部门
let organNameList = [];
if (organTree.length > 0) {
  organTree[0].children.forEach(organ => {
    let organObject = {
      name: organ.data.name,
      organId: organ.data.organId
    };
    organNameList.push(organObject);
  });
}

isdialogOptions.value.forEach(e => {
  if (e.prop == "useOrgans") {
    e.inputProps.options = [];
    organNameList.forEach(item => {
      let organNameObj = {
        label: item.name,
        value: item.organId
      };
      e.inputProps.options.push(organNameObj);
    });
  }
});

let organMap = new Map();
organNameList.forEach(item => {
  organMap.set(item.organId, item.name);
});

//StrapType:设备类型
const strapType = [];
if (organInfo.value.length > 0) {
  strapType = organInfo.value[0].children[0].children.map(
    ({ data: { organId, name } }) => ({ organId, name })
  );
}

let ownerList = [];
let typeMap = new Map();
strapType.forEach(e => {
  const ownerObj = {
    label: e.name,
    value: e.organId
  };
  ownerList.push(ownerObj);
});

ownerList.forEach(e => {
  mapList.set(e.value, e.label);
});

// 当选择中 使用部门后 , 调 APi 获取 设备类型的元素 此次遍历获取 配置项中 归属单位所对应
isdialogOptions.value.forEach(e => {
  if (e.prop == "owner") {
    e.inputProps.options = ownerList;
    e.events.change = function(value, evt) {
      geteqptType({ owners: [value] }).then(resq => {
        //循环查找到设备类型
        isdialogOptions.value.forEach(c => {
          if (c.prop == "eqptType") {
            FilterRef.value.setFieldsValue({
              eqptType: null
            });
            let arry = [];
            let items = [];
            let keyword = "座椅";
            const regex = new RegExp(keyword, "i"); // i表示不区分大小写
            resq.data.forEach((item, index) => {
              // if (regex.test(item.typeName)) {
                // children和label的值根据后端接口的实际情况书写
                c.inputProps.defaultProps = {
                  children: "children",
                  label: "typeName",
                  value: "typeId"
                };
                items.push(item);
                arry = items;
              // }
            });
            c.inputProps.data = arry;
            // 重写 设备类型 change事件 拿到对应 value
            c.events.change = function(value, evt) {
              typeId = value;
            };
          }
        });
      });
    };
  }
});

var coordinate = null;

const ismapOptions = ref(mapOptions);
ismapOptions.value[0].inputProps.options.unshift({
  label: "全部",
  value: "全部"
});
const thresholdDialogVisible = ref(false);
const addDialogVisible = ref(false);
const saveDialogVisible = ref(false);
const isEdit = ref(false);
const isSelect = ref(false);
const rowInd = ref(0);
const colInd = ref(0);
const timer = ref();
const addTilte = ref("");
// 记得让columns.ts里面的对应thresholdListColumns的字段名和后端数据保持一致
const thresholdData = ref([]);

//获取登录用户信息
const CacheState = JSON.parse(
  window.localStorage.getItem("CacheState") as string
);
const name = ref("");
const userId = ref("");
const organId = ref("");
const organName = ref("");
name.value = CacheState.user.userInfo.name;
userId.value = CacheState.user.userInfo.userId;
organId.value = CacheState.user.userInfo.organId;
organName.value = CacheState.user.userInfo.organName;

const upload = ref<UploadInstance>();
//导入
const handleImport = (file: any) => {
  const index = file.name.lastIndexOf("."); // 根据文件名找到最后一个‘.’的索引
  const suffixName = file.name.substr(index); // 根据索引截取，得到后缀名
  if (suffixName !== ".xlsx" && suffixName !== ".xls") {
    ElMessage({
      message: "此文件不是excel文件",
      type: "warning"
    });
    upload.value?.clearFiles();
  } else {
    const formData = new FormData();
    formData.append("multipartFile", file.raw);
    formData.append("id", userId.value);
    formData.append("name", name.value);
    formData.append("organId", organId.value);
    formData.append("organName", organName.value);
    seatImport(formData)
      .then(res => {
        if (res.code == "1") {
          getData();
          ElMessage({
            message: "导入成功",
            type: "success"
          });
          upload.value!.clearFiles();
        } else {
          ElMessage.error("导入失败");
          upload.value!.clearFiles();
        }
      })
      .catch(err => {
        ElMessage.error(err?.message || "导入失败");
        upload.value!.clearFiles();
      });
  }
};

//获取当前时间
const getCurrentTime = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = ("0" + (now.getMonth() + 1)).slice(-2);
  const day = ("0" + now.getDate()).slice(-2);
  const formattedTime = `${year}${month}${day}`;
  return formattedTime;
};

/*
 * @param {Obj} 表单值
 * @return {void}
 * */
const handleCreate = val => {
  timer.value = new Date().getTime();
  if (val === "threshold") {
    // 弹窗标题
    thresholdDialogVisible.value = true;
    addTilte.value = "设置维护提醒";
  } else if (val === "export") {
    //导出
    exportPageList(search?.value).then(res => {
      const a = document.createElement("a");
      a.href = URL.createObjectURL(new Blob([res]));
      a.download = `旅客座椅管理${getCurrentTime()}.xlsx`;
      a.click();
    });
  } else if (val === "download") {
    seatModuleDown().then(res => {
      const a = document.createElement("a");
      a.href = URL.createObjectURL(new Blob([res]));
      a.download = "旅客座椅导入模板.xlsx";
      a.click();
    });
  } else if (val === "import") {
  } else {
    FilterRef.value = {};
    dialogState = "add";
    isdialogOptions.value.forEach(e => {
      e.defaultValue = "";
    });
    nowData.value = {};
    // 弹窗标题
    dialogState = "add";
    addTilte.value = "新增设施设备";
    addDialogVisible.value = true;
  }
};

const vcoordinate = ref("");
var organization = {};

var dialogState = "";
var eqptId = 0;

let useOranList = [];

let rowOwner = "";

function flattenTree(tree) {
  var result = [];

  function flatten(node) {
    let item = {
      typeId: node.typeId,
      typeName: node.typeName
    };
    result.push(item);

    if (node.children && node.children.length > 0) {
      node.children.forEach(function(child) {
        flatten(child);
      });
    }
  }

  flatten(tree);

  return result;
}

/**
 * 编辑处理
 *
 * @param {object} row - 要编辑的行数据
 */
const handleEdit = row => {
  dialogState = "edit";
  eqptId = row.eqptId;
  saveDialogVisible.value = true;
  coordinate = row.coordinate;
  typeId = row.typeId;

  if (row.useOrgans) {
    // 遍历 useOrgans 数组中的每个元素
    row?.useOrgans.forEach(item => {
      // 如果 organName 不为空并且不为 ' '，则执行以下操作
      if (item.organName != " " && item.organName != null) {
        organMap.forEach((key, value) => {
          if (key == item.organName) {
            useOranList.push(value);
          }
        });
      }
    });
  }

  //点击地图坐标图标返回地图页面
  isdialogOptions.value.forEach(e => {
    if (e.prop == "coordinate") {
      e.events.click = function(value, evt) {
        handleBack();
      };
    }
  });

  // 该循环用于进行编辑页面数据回显，需要字段对应
  isdialogOptions.value.forEach(e => {
    // 如果行数据的属性不为 null，则将其作为默认值赋给对应的 dialogOptions 元素
    if (row[e.prop] != null || e.prop != "eqptType") {
      e.defaultValue = row[e.prop];
    } // 如果属性为 'eqptType'，则将 typeName 属性作为默认值赋给对应的 dialogOptions 元素
    if (e.prop == "eqptType") {
      mapList.forEach((key, value) => {
        if (key == row.ownerName) {
          //获取设备类型
          geteqptType({ owners: [value] }).then(resq => {
            isdialogOptions.value.forEach(c => {
              if (c.prop == "eqptType") {
                let arry = [];
                let items = [];
                let keyword = "旅客";
                FilterRef.value.setFieldsValue({
                  eqptType: null
                });
                const regex = new RegExp(keyword, "i"); // i表示不区分大小写
                resq.data.forEach((item, index) => {
                  // if (regex.test(item.typeName)) {
                    // children和label的值根据后端接口的实际情况书写
                    c.inputProps.defaultProps = {
                      children: "children",
                      label: "typeName",
                      value: "typeId"
                    };

                    items.push(item);
                    arry = items;
                  // }
                });

                c.inputProps.data = arry;

                //遍历的设备类型树
                const nowData = flattenTree(arry[0]);
                nowData.forEach(item => {
                  if (item.typeId == row.typeId) {
                    FilterRef.value.setFieldsValue({
                      eqptType: item.typeName
                    });
                    typeId = row.typeId;
                  }
                });
                c.events.change = function(value, evt) {
                  typeId = value;
                };
              }
            });
          });
        }
      });
    }
    // 如果属性为 'useOrgans'，则将 useOranList 作为默认值赋给对应的 dialogOptions 元素，并将 useOranList 置为空数组
    if (e.prop == "useOrgans") {
      e.defaultValue = useOranList;
      useOranList = [];
    }
    // 如果属性为 'useOrgans'，则将 useOranList 作为默认值赋给对应的 dialogOptions 元素，并将 useOranList 置为空数组
    if (e.prop == "coordinate") {
      if (!row.coordinate) {
        e.defaultValue = null;
      } else {
        vcoordinate.value = `(${row?.coordinate?.latitude} , ${row?.coordinate?.longitude})`;
      }
      e.defaultValue = vcoordinate.value;
      e.value = vcoordinate.value;
    }
    // 如果属性为 'owner'，根据 row.ownerName 在 mapList 中找到对应的键并将其作为默认值赋给对应的 dialogOptions 元素
    if (e.prop == "owner") {
      mapList.forEach((key, value) => {
        if (row.ownerName) {
          if (key == row.ownerName) {
            e.defaultValue = value;
          }
        } else {
          e.defaultValue = null;
        }
      });
      //e.defaultValue=row.ownerName
      rowOwner = row.ownerName;
    }
    if (e.prop == "position") {
      if (row.position == "undefined") {
        e.defaultValue = null;
      }
    }
  });

  /*
   * @param {Obj} 表单值
   * @return {void}
   * */
  timer.value = new Date().getTime();
  addTilte.value = "编辑设施设备";
};

/*
 * @param {Obj} 表单值
 * @return {void}
 * */
const handleSubmit = (k: any) => {
  thresholdDialogVisible.value = false;
  isEdit.value= false;
  isSelect.value=false
};
// 点击取消
const handleCancel = () => {
  isEdit.value= false;
  isSelect.value=false
  // 点取消 地图清空
  vcoordinate.value = "";
  nowData.value = {};
  //清空设备类型选项
  isdialogOptions.value.forEach(e => {
    if (e.prop == "eqptType") {
      e.inputProps.data = [];
    }
  });
  FilterRef.value = {};
  thresholdDialogVisible.value = false;
  addDialogVisible.value = false;
  saveDialogVisible.value = false;
};

let nowData = ref({});
// 点击下一步
/*
 * @param {void}
 * @return {void}
 * */
const handleNext = () => {
  addDialogVisible.value = false;
  saveDialogVisible.value = true;
  nextTick(() => {
    FilterRef.value.setFieldsValue({
      coordinate: vcoordinate.value
    });
  });
  if (Object.keys(nowData.value).length) {
    isdialogOptions.value.forEach(item => {
      if (item.prop == "eqptCode") {
        item.defaultValue = nowData.value?.eqptCode || "";
      }
      if (item.prop == "eqptModel") {
        item.defaultValue = nowData.value?.eqptModel || "";
      }
      if (item.prop == "eqptName") {
        item.defaultValue = nowData.value?.eqptName || "";
      }
      if (item.prop == "position") {
        item.defaultValue = nowData.value?.position || "";
      }
      if (item.prop == "coordinate") {
        item.defaultValue = nowData.value?.coordinate || "";
      }
      if (item.prop == "useOrgans") {
        item.defaultValue = nowData.value?.useOrgans || [];
      }
      if (item.prop == "owner") {
        item.defaultValue = nowData.value?.owner || "";
      }
      if (item.prop == "eqptType") {
        item.defaultValue = nowData.value.eqptType;
      }
    });
  }
};

/*
 * @param {void}
 * @return {void}
 * */
// 点击返回
const handleBack = () => {
  saveDialogVisible.value = false;
  addDialogVisible.value = true;
  nowData.value = FilterRef.value.getParams();
};

/*
 * @param {void}
 * @return {void}
 * */
// 点击保存
const handleSave = async () => {
  let flag = await FilterRef.value?.validateRuleFormRef();
  if (flag) {
    const data = FilterRef.value.getParams();

    if (Object.keys(mapPoint.value).length === 0) {
      if(dialogState == "add"){
        data.coordinate = undefined;
      }else{
        let location = data.coordinate.split(',');
        data.coordinate = {latitude: location[0].substr(1).trim(), longitude:location[1].substr(0, location[1].length-1).trim()};
      }
    } else {
      data.coordinate = mapPoint.value;
    }

    let use = data.useOrgans;
    data.useOrgans = [];
    if (data.position == undefined) {
      data.position = "";
    }
    if (data.eqptModel == undefined) {
      data.eqptModel = " ";
    }
    if (use.length) {
      for (let i of use) {
        data.useOrgans.push({
          organName: organMap.get(i)
        });
      }
    } else {
      data.useOrgans.push({
        organName: " "
      });
    }
    data.eqptType = 2;
    // 数据库非空字段
    data.typeId = typeId;
    if (dialogState == "add") {
      // 顶级后端 ，增加要 字符串 修改又要对象 organization这个字段
      data.owner = {
        id: data.owner,
        name: mapList.get(data.owner),
        organName: mapList.get(data.owner)
      };

      for (let el of data) {
        if (typeof el === "string") {
          el = el.trim();
        }
      }

      append(data)
        .then(res => {
          ElMessage({
            message: "添加成功",
            type: "success"
          });

          isdialogOptions.value.forEach(e => {
            if (e.prop == "eqptType") {
              e.inputProps.data = [];
            }
          });
          getData();
          saveDialogVisible.value = false;
        })
        .catch(err => {
          ElMessage.error(err?.message || "保存失败");
        });
    } else {
      //   这是修改
      if (mapList.get(data.owner)) {
        data.owner = {
          name: mapList.get(data.owner)
        };
      } else {
        data.owner = {
          name: rowOwner
        };
      }

      data.eqptId = eqptId;

      for (let el of data) {
        if (typeof el === "string") {
          el = el.trim();
        }
      }

      change(data).then(res => {
        ElMessage({
          message: "编辑成功",
          type: "success"
        });
        isdialogOptions.value.forEach(e => {
          if (e.prop == "eqptType") {
            e.inputProps.data = [];
          }
        });
        getData();
        saveDialogVisible.value = false;
      });
    }
  }
};

// 表单验证规则
const rules = reactive<FormRules>({
  eqptCode: [
    {
      required: true,
      message: "请输入设备编号",
      trigger: "change"
    }
  ],
  eqptType: [
    {
      required: true,
      message: "请选择设备类型",
      trigger: "change"
    }
  ],
  eqptName: [
    {
      required: true,
      message: "请输入设备名称",
      trigger: "change"
    }
  ],
  owner: [
    {
      required: true,
      message: "请选择归属单位",
      trigger: "change"
    }
  ]
});

const current = ref(1);
const pageSize = ref(10);
const total = ref(0);
const tabledata = ref([]);
const search = ref({});

const pager = computed(() => ({
  currentPage: current.value,
  pageSize: pageSize.value,
  total: total.value,
  pageCount: Math.ceil(total.value / pageSize.value) || 1
}));

/*
 * @param {void}
 * @return {void}
 * */
// 获取数据
const getData = () => {
  const searchList = {
    eqptCode: search.value?.eqptCode,
    regions: search.value?.regions,
    terminals: search.value?.terminals,
    order: [
      {
        column: "eqptCode",
        method: "desc"
      }
    ]
  };

  const playout = {
    pageNum: current.value,
    pageSize: pageSize.value,
    condition: searchList
  };

  //调用api

  if (playout.condition?.regions?.length === 0) {
    delete playout.condition.regions;
  }
  if (playout.condition?.terminals?.length === 0) {
    delete playout.condition.terminals;
  }

  seatPageList(playout)
    .then(res => {
      tabledata.value = res?.data?.list;
      total.value = res?.data?.total;

      for (let i = 0; i < tabledata.value.length; i++) {
        tabledata.value[i].id = i + 1;
      }
    })
    .catch(err => {
      ElMessage.error(err?.message || "获取失败");
    });
};

/*
 * @param {number} 当前页面数
 * @return {void}
 * */
//分页
const changeCurrent = (value: number) => {
  current.value = value;
  getData();
};
const changePageSize = (size: number) => {
  pageSize.value = size;
  getData();
};

/*
 * @param {Obj} 当前行数 的信息
 * @return {void}
 * */
//删除
const DeletRow = (row: any) => {
  const code = seatDeleteRow(row.eqptId);
  code.then(res => {
    if (res?.code) {
      getData();
      ElMessage({
        message: "删除成功",
        type: "success"
      });
    } else {
      ElMessage.error("删除失败");
    }
  });
};

/*
 * @param {any}  当前行信息
 * @return {void}
 * */
// 单击 出现输入框
// setThreshold 和 isAlarm 的字段名和后端数据保持一致
const cellClick = (val: any) => {
  if (val.column.property === "setThreshold") {
    isEdit.value = true;
    isSelect.value = false;
    rowInd.value = val.$index;
    colInd.value = val.cellIndex;
  } else if (val.column.property === "isAlarm") {
    isSelect.value = true;
    isEdit.value = false;
    rowInd.value = val.$index;
    colInd.value = val.cellIndex;
  }
};

/**
 * 隐藏函数
 *
 * @param {number} row - 行数，用于确定隐藏的行
 * @param {number} column - 列数，可选参数，用于确定隐藏的列
 * @param {Event} event - 事件对象，用于处理触发隐藏的事件
 * @return {void}
 */
const hiddenMe = (row, column, event) => {
  if (column != undefined) {
    isEdit.value = false;
    isSelect.value = false;
  }
};
// 提交信息
const Submit = () => {};

/**
 * 表单重置函数
 *
 * @param {FilterDataType} data - 过滤数据，用于重置搜索条件
 * @return {void} - 没有明确的返回值
 */
const searchReset = (data: FilterDataType) => {
  search.value = data;
  search.value["regions"].checkAll = false;
  pager.value.currentPage = 1;
  pager.value.pageSize = 10;
  getData();
};

/**
 * 获取terminal字典
 *
 * @param {any} data - 请求数据，用于获取终端资源
 * @return {Promise<void>} - 异步函数 ，获取数据结果的 异步状态
 */
//获取terminal字典
const getTerminal = async (data: any) => {
  await getResource(data).then(res => {
    for (let i = 0; i < ismapOptions.value.length; i++) {
      if (ismapOptions.value[i].prop == "terminals") {
        ismapOptions.value[i].inputProps.options = res.data.properties.meta;
      }
    }
  });
};

/**
 * 获取区域字典
 *
 * @param {any} data - 请求数据，用于获取终端资源
 * @return {Promise<void>} - 异步函数 ，获取数据结果的 异步状态
 */
//获取区域数据字典
const getResource_area = async (data: any) => {
  await getResource(data).then(res => {

    let regions = res.data.properties.meta;
    for(let i = 0; i < regions.length; i++){
      var region  = {
        id: i,
        area: regions[i].label,
        historicalAverage: "30",
        isAlarm: regions[i].alert?"是":"否",
        setThreshold: "13"
      };
      thresholdData.value.push(region);
    }



    for (let i = 0; i < ismapOptions.value.length; i++) {
      if (ismapOptions.value[i].prop == "regions") {
        res.data.properties.meta.unshift({ label: "全部", value: "" });
        ismapOptions.value[i].inputProps.options = res.data.properties.meta;
        ismapOptions.value[i].inputProps.options[1].alert = true;
      }
    }
  });
};

/**
 * 地图点击事件
 *
 * @param {any} evt - 地图点击事件对象
 * @return {void}
 */
const mapClick = (evt: any) => {
  store.BNMap.removeGraphicsLayer("clickLayer");
  // 向地图添加临时图层
  const clickLayer = store.BNMap.creatGraphicsLayer({ id: "clickLayer" });
  clickLayer.removeAll();
  // 创建点
  const point = store.BNMap.createPoint({
    x: evt.mapPoint.x,
    y: evt.mapPoint.y,
    spatialReference: evt.mapPoint.spatialReference
  });
  // store.BNMap.setCenter(point);
  // 创建图片
  const symbolStyle = store.BNSymbol.PictureMarkerSymbol(image.point, 20, 25);
  // 创建要素
  const picgraphic = store.BNMap.graphic(point, symbolStyle);
  // 添加到地图
  clickLayer.add(picgraphic);
  store.BNMap.addGraphicsLayer(clickLayer);
  // 将相关信息保存到变量
  mapPoint.value.latitude = evt.mapPoint.x.toFixed(4);
  mapPoint.value.longitude = evt.mapPoint.y.toFixed(4);
  // 地图区域值暂时为空

  isdialogOptions.value.forEach(e => {
    if (e.prop == "coordinate") {
      e.defaultValue = `(${mapPoint.value.latitude} , ${mapPoint.value.longitude})`;
      e.value = `(${mapPoint.value.latitude} , ${mapPoint.value.longitude})`;
      vcoordinate.value = `(${mapPoint.value.latitude} , ${mapPoint.value.longitude})`;
    }
  });
};
const mapPoint = ref({});



onBeforeMount(() => {
  getTerminal("terminal");
  getData();
  getResource_area("resource_area");
});
</script>

<style scoped>
.layoutCard /deep/ .el-form-item__label:nth-child(1) {
  width: 110px !important;
}
</style>
